import React, { Component } from "react";
import {
  Form,
  Input,
  Button,
  Modal,
  DatePicker,
  Transfer,
  message,
  Tag,
  Select,
  Radio,
} from "antd";
import moment from "moment";
import axios from "axios";
import qs from "qs";
import OrgTree from "./OrgTree";
import "../mock/user003001";
import "../mock/user003002";
const { Option } = Select;
Date.prototype.Format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "H+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S+": this.getMilliseconds(), //毫毛
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
  return fmt;
};
export default class EditTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      addVisible: false,
      //   mockData: ["李亮", "张明", "李飞", "王培"], //职工列表
      hostMockData: [], //职工列表
      joinMockData: [], //职工列表
      hostTargetKeys: [props.record.meetingHost],
      joinTargetKeys: props.record.meetingJoin,
      //   hostSelectedKeys: [props.record.meetingHost],
      //   joinSelectedKeys: [props.record.meetingJoin],
      rules: [
        {
          required: false,
          message: "此项不可为空",
        },
      ],
      treeData: [],
      getDataSource: props.getDataSource,
    };
    this.formRef = React.createRef();
    this.setTreeData = this.setTreeData.bind(this);
    this.treeOnSelect = this.treeOnSelect.bind(this);
  }

  /**初始化数据 */
  initData = (row) => {
    // console.log(row);
    this.setState({
      rowsData: row,
      enable: row.enable, //外部数据
      addVisible: true, //*弹出,
      isEnable: row.enable.length > 0 ? "500px" : "0px",
      startTime: row.meetingTime,
      endTime: row.meetingEndTime,
    });

    // /**等待form渲染 */
    setTimeout(() => {
      this.formRef.current.setFieldsValue({
        address: row.meetingAddress,
        content: row.meetingContent,
        remark: row.remark,
        leaders: row.meetingLeaders,
        responsibleDepartment: row.responsibleDepartment,
        isEnable: row.enable.length > 0 ? "500px" : "0px",
      });

      /**手动添加必选样式（假） */
      var dateLable = document.querySelectorAll(
        ".ant-form-item-label label[for='add-meeting_date']"
      );
      var timeLable = document.querySelectorAll(
        ".ant-form-item-label label[for='add-meeting_time']"
      );

      dateLable.forEach((i) => i.classList.add("ant-form-item-required"));
      timeLable.forEach((i) => i.classList.add("ant-form-item-required"));
    }, 100);
  };

  /**添加主持人 */
  handleHostChange = (hostTargetKeys) => {
    this.setState({ hostTargetKeys });
  };
  /**添加参会人 */
  handleJoinChange = (joinTargetKeys) => {
    this.setState({ joinTargetKeys });
  };
  /**机构数据 */
  setTreeData = (treeData) => {
    setTimeout(() => {
      this.setState({ treeData });
    }, 0);
  };

  /*点击部门列表,展示部门人员 */
  treeOnSelect = (isHost, value) => {
    console.log(value);
    // this.getMock(isHost, value);
    axios
      .get("searchUsers.rst?orgId=" + value[0])
      .then((res) => {
        let response = res.data;
        // response = response.data;
        console.log(response);
        if (response.resultCode === 0) {
          let res = response.result.data;
          if (response.result.total === 0) {
            res = [];
          }
          /**清空并关闭添加表单 */
          if (isHost) {
            this.setState({
              hostMockData: res.map((person) => {
                return {
                  key: person.EMPID + "_" + person.EMPNAME,
                  title: person.EMPID + "_" + person.EMPNAME,
                };
              }),
            });
          } else {
            this.setState({
              joinMockData: res.map((person) => {
                return {
                  key: person.EMPID + "_" + person.EMPNAME,
                  title: person.EMPID + "_" + person.EMPNAME,
                };
              }),
            });
          }
        } else {
          // message.error("人员数据请求失败");
        }
      })
      .catch((error) => {
        message.error("人员数据请求失败");
      });
  };

  /**弹出对话框 */
  showAddModal = () => {
    const record = this.props.record;
    /**弹出 */
    this.setState({
      addVisible: true,
    });
    /**等待form渲染 */
    setTimeout(() => {
      this.formRef.current.setFieldsValue({
        address: record.meetingAddress,
        content: record.meetingContent,
        meetingRoom: record.meetingRoom,
      });

      /**手动添加必填样式 */
      var dateLable = document.querySelectorAll(
        ".ant-form-item-label label[for='edit-meeting_date']"
      );
      var addressLable = document.querySelectorAll(
        ".ant-form-item-label label[for='edit-meeting_address']"
      );
      var contentLable = document.querySelectorAll(
        ".ant-form-item-label label[for='edit-meeting_content']"
      );

      dateLable.forEach((i) => i.classList.add("ant-form-item-required"));
      addressLable.forEach((i) => i.classList.add("ant-form-item-required"));
      contentLable.forEach((i) => i.classList.add("ant-form-item-required"));
    }, 100);
  };

  onFinish = (values) => {
    /**表单字段在不做改动时返回时会为undefined，需要手动判断 */

    let pass = true;
    let remindTime;
    let messCon = "";
    /**表单返回值 currVal*/
    const currVal = this.formRef.current.getFieldsValue();
    console.log(currVal);
    // console.log(currVal)
    const date = document.querySelector(".edit-modal #edit-meeting_date");
    /**判断日期，地点，内容 */
    if (!currVal.address.length || !currVal.content.length) {
      pass = false;
      messCon = "会议地点及内容";
    }
    /**判断主持人和参会人 */
    // if (this.state.hostTargetKeys.length === 0) {
    //   pass = false;
    //   messCon = "主持人";
    // }
    // if (this.state.joinTargetKeys.length === 0) {
    //   pass = false;
    //   messCon = "参会人";
    // }
    if (date.value.length === 0) {
      pass = false;
      messCon = "会议时间";
    }

    if (values.remindTime && date.value) {
      console.log(values.remindTime);
      let meetingDate = new Date(date.value.replace(/\-/g, "/")).getTime();
      remindTime = new Date(meetingDate - values.remindTime * 60 * 1000).Format(
        "yyyy-MM-dd HH:mm:ss"
      );
    }
    /** */
    if (pass) {
      this.setState({ loading: true });

      /**修改会议数据 */
      axios({
        url: "updatemeeting.rst",
        method: "post",
        data: qs.stringify({
          id: this.props.record.key,
          meetingDate: date.value.split(" ")[0],
          meetingTime: date.value.split(" ")[1],
          locale: currVal.address,
          theme: currVal.content,
          host: this.state.hostTargetKeys.join(),
          participator: this.state.joinTargetKeys.join(),
          meetingRoom: currVal.meetingRoom,
          remindTime: remindTime,
          enable: currVal.enable ? currVal.enable : this.props.record.enable,
        }),
      })
        .then((res) => {
          let response = res.data;
          if (response.resultCode === 0) {
            /**清空并关闭添加表单 */
            message.success("提交成功");
            this.setState({ loading: false, addVisible: false });
            /**重新渲染会议列表 */
            this.props.getDataSource();
          } else {
            message.error("提交失败");
          }
        })
        .catch((error) => {
          message.error("提交失败");
        });
    } else {
      /**有字段为空 */
      message.error(messCon + "字段不可为空！");
    }
  };

  handleCancel = () => {
    const { meetingHost, meetingJoin } = this.props.record;
    /**清空修改表单状态 */
    // this.formRef.current.resetFields();
    this.setState({
      hostTargetKeys: [meetingHost],
      joinTargetKeys: meetingJoin,
    });
    // this.setState({ loading: false, addVisible: false });
  };

  componentDidMount() {
    // this.getMock();
    // var hostLable = document.querySelector(
    //   ".ant-form-item-label label[for='edit-meeting_host']"
    // );
    // var joinLable = document.querySelector(
    //   ".ant-form-item-label label[for='edit-meeting_join']"
    // );
    // hostLable.classList.add("red");
  }
  /**关闭Tag */
  handleHostTagClose = (removedTag) => {
    const hostTargetKeys = this.state.hostTargetKeys.filter(
      (hostTargetKeys) => hostTargetKeys !== removedTag
    );
    console.log(hostTargetKeys);
    this.setState({ hostTargetKeys });
  };
  handleJoinTagClose = (removedTag) => {
    const joinTargetKeys = this.state.joinTargetKeys.filter(
      (joinTargetKeys) => joinTargetKeys !== removedTag
    );
    console.log(joinTargetKeys);
    this.setState({ joinTargetKeys });
  };
  /*遍历插入Tag */
  hostForMap = (tag) => {
    // console.log(tag);
    return (
      <span key={tag} style={{ display: "inline-block", marginBottom: 16 }}>
        <Tag
          closable
          color="geekblue"
          onClose={(e) => {
            e.preventDefault();
            this.handleHostTagClose(tag);
          }}
        >
          {tag}
        </Tag>
      </span>
    );
  };
  joinForMap = (tag) => {
    // console.log(tag);
    return (
      <span key={tag} style={{ display: "inline-block", marginBottom: 16 }}>
        <Tag
          closable
          color="blue"
          onClose={(e) => {
            e.preventDefault();
            this.handleJoinTagClose(tag);
          }}
        >
          {tag}
        </Tag>
      </span>
    );
  };

  render() {
    const { addVisible, loading } = this.state;
    /**添加会议数据 */

    const {
      rules,
      hostMockData,
      joinMockData,
      hostTargetKeys,
      joinTargetKeys,
      treeData,
    } = this.state;
    const { meetingDate, meetingTime } = this.props.record;
    const hostTag = hostTargetKeys.map(this.hostForMap);
    const joinTag = joinTargetKeys.map(this.joinForMap);
    return (
      <>
        <Button type="primary" onClick={this.showAddModal}>
          修改
        </Button>
        <Modal
          visible={addVisible}
          title="会议信息"
          centered
          onCancel={this.handleCancel}
          //   onOk={this.handleAdd}
          width={1000}
          //   onCancel={this.handleCancel}
          footer={null}
          className="edit-modal"
          destroyOnClose={true}
        >
          <Form
            name="edit-meeting"
            onFinish={this.onFinish}
            className="search-meet"
            ref={this.formRef}
          >
            <Form.Item name="date" label="会议时间" shouldUpdate rules={rules}>
              <DatePicker
                format="YYYY-MM-DD HH:mm"
                defaultValue={moment(
                  meetingDate + " " + meetingTime,
                  "YYYY-MM-DD HH:mm"
                )}
              />
            </Form.Item>
            <Form.Item name="remindTime" label="提醒时间">
              <Select
                style={{ width: 180 }}
                allowClear
                defaultValue={this.props.record.remindTime.substr(11)}
                // dropdownRender={(menu) => (
                //   <div>
                //     {menu}
                //     <Divider style={{ margin: "4px 0" }} />
                //     <div
                //       style={{
                //         display: "flex",
                //         flexWrap: "nowrap",
                //         padding: 8,
                //       }}
                //     >
                //       <DatePicker
                //         format="YYYY-MM-DD HH:mm"
                //         showTime={{ defaultValue: moment("12:00:00", "HH:mm") }}
                //       />
                //     </div>
                //   </div>
                // )}
              >
                <Option value="10">提前10分钟</Option>
                <Option value="15">提前15分钟</Option>
                <Option value="30">提前30分钟</Option>
                <Option value="60">提前60分钟</Option>
              </Select>
            </Form.Item>
            <Form.Item name="address" label="地点" rules={rules}>
              <Input />
            </Form.Item>
            <Form.Item name="meetingRoom" label="会议室">
              <Input />
            </Form.Item>
            <Form.Item name="content" label="内容" rules={rules}>
              <Input />
            </Form.Item>
            <Form.Item name="host" label="主持人">
              {hostTag}
              <OrgTree
                treeData={treeData}
                setTreeData={this.setTreeData}
                treeOnSelect={this.treeOnSelect}
                isHost={true}
              />
              <Transfer
                dataSource={hostMockData}
                targetKeys={hostTargetKeys}
                // selectedKeys={hostTargetKeys}
                showSearch
                listStyle={{
                  width: 250,
                  height: 200,
                }}
                operations={["添加", "移出"]}
                onChange={this.handleHostChange}
                render={(item) => `${item.title}`}
                disabled={hostTargetKeys.length}
              />
            </Form.Item>
            <Form.Item name="join" label="参加人">
              {joinTag}
              <OrgTree
                treeData={treeData}
                setTreeData={this.setTreeData}
                treeOnSelect={this.treeOnSelect}
                isHost={false}
              />
              <Transfer
                dataSource={joinMockData}
                targetKeys={joinTargetKeys}
                // selectedKeys={joinTargetKeys}
                showSearch
                listStyle={{
                  width: 250,
                  height: 200,
                }}
                operations={["添加", "移出"]}
                onChange={this.handleJoinChange}
                render={(item) => item.title}
              />
            </Form.Item>
            <Form.Item name="enable" label="是否启用">
              <Radio.Group
                name="enable"
                defaultValue={this.props.record.enable}
              >
                <Radio value={1}>启用</Radio>
                <Radio value={0}>不启用</Radio>
              </Radio.Group>
            </Form.Item>
            <Button type="primary" htmlType="submit" loading={loading}>
              确定
            </Button>
          </Form>
        </Modal>
      </>
    );
  }
}
